package com.hmdp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final StringRedisTemplate redisTemplate;

    private final ShopTypeMapper shopTypeMapper;

    public ShopTypeServiceImpl(StringRedisTemplate redisTemplate, ShopTypeMapper shopTypeMapper) {
        this.redisTemplate = redisTemplate;
        this.shopTypeMapper = shopTypeMapper;
    }

    @Override
    public Result queryTypeList() {
        String cacheShopTypeList = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + "type");
        if (!StringUtils.isEmpty(cacheShopTypeList)) {
            return Result.ok(JSON.parseArray(cacheShopTypeList, ShopType.class));
        }
        QueryWrapper<ShopType> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        List<ShopType> shopTypes = shopTypeMapper.selectList(queryWrapper);
        redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + "type", JSON.toJSONString(shopTypes));
        return Result.ok(shopTypes);
    }
}
